package com.atguigu.lease.common.utills;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {
    private static final SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
    public static String createToken(Long userId, String username){

        //创建jwt的代码
        String jwt = Jwts.builder()
                .setExpiration(new Date(System.currentTimeMillis() + 3600000))//设置过期时间1 小时
                .setId(userId.toString())//设置id
                .setSubject("LOGIN_USER")//设置主题
                .claim("userId", userId)//设置自定义属性
                .claim("username", username)//设置自定义属性
                .signWith(secretKey, SignatureAlgorithm.HS256)//设置签名 第二个参数是算法
                .compact();
        return jwt;
    }
    //校验(解析) token
    public static Claims parseToken(String token){

        if (token==null){
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }

        try{
            JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(secretKey).build();
            return jwtParser.parseClaimsJws(token).getBody();
        }catch (ExpiredJwtException e){
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        }catch (JwtException e){
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
    }
    //测试
    public static void main(String[] args) {
        System.out.println(createToken(1L, "admin"));

    }
}
